package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.*;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.service.HCarReserveService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.entity.OrgDept;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: project
 * @description: 预定车
 * @author: shiliqiang
 * @create: 2019-02-23 14:24
 * @version: 1.0
 */
@Service
public class HCarReserveServiceImpl implements HCarReserveService {

    @Autowired
    private HCarReserveMapper hCarReserveMapper;
    @Autowired
    private HCarCalendarMapper hCarCalendarMapper;
    @Autowired
    private HCarReserveItemMapper hCarReserveItemMapper;
    @Autowired
    private HCarMapper hCarMapper;
    @Autowired
    private HDriverMapper hDriverMapper;
    @Autowired
    private HCarReservePayinfoMapper hCarReservePayinfoMapper;

    @Override
    public ServerResponse<String> updateReserveStatus(HttpServletRequest request, String model) throws Exception {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        OrgDept currentUserDept = FleaOrgUtils.getCurrentUserDept(userId);
        if (currentUserDept==null){
            return ServerResponse.createByErrorMessage("部门不能为空");
        }
        String serviceType = currentUserDept.getServiceType();
        JSONObject jsonObject = JSON.parseObject(model);
        String id = jsonObject.getString("id");
        String reserveStatus = jsonObject.getString("reserveStatus");
        HCarReserve reserve = hCarReserveMapper.selectByPrimaryKey(id);
        if (reserve==null){
            return ServerResponse.createByErrorMessage("没有找到订单信息");
        }
        //当预定拒绝，预定取消，操作是不一样的

        if (reserveStatus.equals(HConstant.D_CAR_RESERVE_STATUS_CANCEL) && !serviceType.equals(HConstant.D_SERVICE_ORG_FLEET)){
            //取消预定信息
            List<HCarReserveItem> carReserveItems = hCarReserveItemMapper.selectByReserveCarId(id);
            if (CollectionUtils.isEmpty(carReserveItems)){
                return ServerResponse.createByErrorMessage("系统出现未知错误，没有找到订单项");
            }
            List<HCar> carList = Lists.newArrayList();
            for (HCarReserveItem item : carReserveItems){
                HCar car = new HCar();
                car.setId(item.getCarId());
                carList.add(car);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String st = sdf.format(reserve.getUseDate());
            String end = sdf.format(reserve.getReturnDate());
            List<HCarCalendar> carCalendars = hCarCalendarMapper.findByTimeAndCarId(carList, st, end);
            if (CollectionUtils.isEmpty(carCalendars)){
                return ServerResponse.createByErrorMessage("系统出现未知错误，没有找到该车的预定日程信息");
            }
            int row = hCarCalendarMapper.deleteByList(carCalendars);
            if (row==0){
                return ServerResponse.createByErrorMessage("删除车辆日程信息失败");
            }
            reserveStatus = HConstant.D_CAR_RESERVE_STATUS_CANCEL;
        }
        reserve.setReserveStatus(reserveStatus);
        int row = hCarReserveMapper.updateByPrimaryKeySelective(reserve);
        if (row<0){
            throw new Exception("更新订单状态失败");
        }

        return ServerResponse.createBySuccessMessage("更新状态成功");
    }

    @Override
    public ServerResponse<FleaPage<HCar>> getRequireCars(HttpServletRequest request, FleaPage<HCar> paging, String reserveCarId) {
        HCarReserve reserve = hCarReserveMapper.selectByPrimaryKey(reserveCarId);
        String deptId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        List<HCar> hCars;
//        hCars = hCarMapper.findTypeAndCarNumber(reserve.getCarNumber(), reserve.getCarType(), deptId);
        hCars = hCarMapper.selectByTypeAndCarNumber(reserve.getCarNumber(), reserve.getCarType(), deptId);
        if (CollectionUtils.isEmpty(hCars)) {
            return ServerResponse.createBySuccessMessage("没有找到符合条件的车");
        }
        //查出 使用开始时间 和使用终止时间内的已经预定车;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String st = sdf.format(reserve.getUseDate());
        String end = sdf.format(reserve.getReturnDate());
        List<HCarCalendar> carCalendars = hCarCalendarMapper.selectByTimeAndCarId(hCars, st, end);
        List<String> newCarIds = Lists.newArrayList();
        //排除日程表中查到的车。剩下的车是符合条件的
        if (CollectionUtils.isNotEmpty(carCalendars)) {
//             String calendarCarId = carCalendars.get(0).getCarId();
//             String newCarId;
//             for (HCar car : hCars){
//                 newCarId = car.getId();
//                 if (!calendarCarId.equals(car.getId())){
//                     newCarIds.add(newCarId);
//                 }
//             }
            return ServerResponse.createBySuccessMessage("车的余量不足");
        }
        RowBounds rowBounds = new RowBounds(paging.getCurPage(),paging.getPageSize());
        for (HCar car : hCars){
            newCarIds.add(car.getId());
        }
        hCars = hCarMapper.selectByCarIdsAndPaging(rowBounds, newCarIds);
        if (CollectionUtils.isEmpty(hCars)) {
            return ServerResponse.createBySuccessMessage("没有找到符合条件的车");
        }
        FleaPage<HCar> fleaPage = new FleaPage<>(hCars);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<FleaPage<HCarReserveItem>> getReserveCarItem(FleaPage<HCar> paging, String reserveCarId) {
        RowBounds rowBounds = new RowBounds(paging.getCurPage(), paging.getPageSize());
        List<HCarReserveItem> items = hCarReserveItemMapper.selectByReserveCarIdAndPaging(rowBounds,reserveCarId);
        FleaPage<HCarReserveItem> fleaPage = new FleaPage<>(items);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<String> insertReserveOrderItem(HttpServletRequest request, String model) throws Exception {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        JSONObject jsonObject = JSON.parseObject(model);
        //预定的内容
        HCarReserve reserve = JSON.parseObject(model, HCarReserve.class);
        reserve = hCarReserveMapper.selectByPrimaryKey(reserve.getId());
        Float totalCost = jsonObject.getFloat("totalCost");
        reserve.setTotalCost(totalCost);
        //预定的车
        List<HCar> carList = JSON.parseArray(jsonObject.getString("cars"), HCar.class);
        //计算车的日程
        List<Date> dates = CalculationDate(reserve.getUseDate(), reserve.getReturnDate());
        List<HCarCalendar> carCalendars = Lists.newArrayList();
//        DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
        int row;
        List<String> carPlateNumberList = null;
        for (HCar car : carList) {
            String carId = car.getCarId();
            for (Date date : dates) {
                HCarCalendar obj = new HCarCalendar();
                obj.setId(FleaStringUtils.getGenerateUUID());
                obj.setCarId(carId);
                obj.setCreateUser(userId);
                obj.setTodayTime(date);
                carCalendars.add(obj);
            }
            //判断当前时间段车是否正在使用
            List<HCarCalendar> carCalendarsList = hCarCalendarMapper.selectByCarIdAndDates(carId, dates);
            carPlateNumberList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(carCalendarsList)) {
                HCar hCar = hCarMapper.selectByPrimaryKey(carId);
                carPlateNumberList.add(hCar.getPlateNumber());


            }
        }
        if (CollectionUtils.isNotEmpty(carPlateNumberList)) {
            StringBuilder sb = new StringBuilder();
            for (String carPlateNumber : carPlateNumberList) {
                sb.append("车牌号：");
                sb.append(carPlateNumber);
                sb.append(",");
                sb.append("在该时间期间可能正在被使用");
            }
            return ServerResponse.createByErrorMessage(sb.toString());
        }


        row = hCarCalendarMapper.insertList(carCalendars);
        if (row == 0) {
            return ServerResponse.createByErrorMessage("添加车日程表记录失败");
        }

        List<HCarReserveItem> carReserveItems = Lists.newArrayList();
        for (HCar car : carList) {
            HCarReserveItem item = new HCarReserveItem();
            item.setCarId(car.getCarId());
            item.setId(FleaStringUtils.getGenerateUUID());
            item.setCreateUser(userId);
            item.setCarReserveId(reserve.getId());
            item.setCurrentDriver(car.getDriverId());
            carReserveItems.add(item);
        }

        row = hCarReserveItemMapper.insertList(carReserveItems);
        if (row == 0) {
            throw new Exception("添加车辆预定项失败");
        }
        //更新预定表状态 更新状态为待确认    组团社或供应商确认后，预定才算完成，这时订单不关闭
        reserve.setReserveStatus(HConstant.D_CAR_RESERVE_STATUS_CONFIRM);
        row = hCarReserveMapper.updateByPrimaryKeySelective(reserve);
        if (row == 0) {
            throw new Exception("更新预定订单失败");
        }
        return ServerResponse.createBySuccessMessage("操作成功");
    }

    //计算中间的时间
    public static List<Date> CalculationDate(Date beginTime, Date endTime) {
        DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
//        System.out.println("开始时间"+FORMATTER.format(beginTime)+"结束时间"+FORMATTER.format(endTime));
        String begin = FORMATTER.format(beginTime);
        String end = FORMATTER.format(endTime);
        List<Date> dates = null;
        if (begin.equals(end)) {
            dates = Lists.newArrayList();
            dates.add(beginTime);
            return dates;
        }
        List<HCarCalendar> list;

        try {
//            String beginTime="2013-01-01";
//            String endTime="2013-01-21";
            Calendar startDay = Calendar.getInstance();
            Calendar endDay = Calendar.getInstance();
            startDay.setTime(beginTime);
            endDay.setTime(endTime);
            // 给出的日期开始日比终了日大则不执行打印
            list = new ArrayList<>();
            HCarCalendar s1 = new HCarCalendar();
            s1.setTodayTime(beginTime);
            list.add(s1);
            if (startDay.compareTo(endDay) <= 0) {
                //现在打印中的日期
                while (true) {
                    HCarCalendar s = new HCarCalendar();
                    // 日期加一
                    startDay.add(Calendar.DATE, 1);
                    // 日期加一后判断是否达到终了日，达到则终止打印
                    if (startDay.compareTo(endDay) == 0) {
                        break;
                    }
                    s.setTodayTime(startDay.getTime());
                    list.add(s);
                }
                HCarCalendar s2 = new HCarCalendar();
                s2.setTodayTime(endTime);
                list.add(s2);
            }
            dates = Lists.newArrayList();
            for (HCarCalendar customer : list) {
                dates.add(customer.getTodayTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dates;
    }

    @Override
    public ServerResponse<FleaPage<HCarReserve>> getUnfinishedCarReserveList(FleaPage<HCarReserve> paging, HttpServletRequest request, String reserveStatus) {
        OrgDept currentUserDept = FleaOrgUtils.getCurrentUserDept(request);
        if (currentUserDept == null) {
            return ServerResponse.createBySuccess();
        }

        String deptUuid = currentUserDept.getDeptUuid();
        RowBounds rowBounds = new RowBounds(paging.getCurPage(), paging.getPageSize());
        String payStatus = HConstant.D_CAR_PAY_STATUS_NO;
        List<HCarReserve> hCarReserves = hCarReserveMapper.selectFleetDeptUuid(rowBounds, deptUuid, reserveStatus, payStatus);
        FleaPage<HCarReserve> fleaPage1 = new FleaPage<>(hCarReserves);
        if (CollectionUtils.isNotEmpty(hCarReserves)) {
            List<HCarReserve> reserves = Lists.newArrayList();
            for (HCarReserve reserve : hCarReserves) {
                HCarReserve obj = new HCarReserve();
                obj.setId(reserve.getId());
                ;
                obj.setUseDeptId(reserve.getUseDeptId());
                obj.setUseDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getUseDeptId())).getDeptName());
                obj.setProvideDeptId(reserve.getProvideDeptId());
//                obj.setProvideDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getProvideDeptId())).getDeptName());
                obj.setReserveStatus(reserve.getReserveStatus());
                obj.setCreateUser(reserve.getCreateUser());
                obj.setCarNumber(reserve.getCarNumber());
                obj.setCarType(reserve.getCarType());
                obj.setStartAddress(reserve.getStartAddress());
                obj.setEndAddress(reserve.getEndAddress());
                obj.setReturnDate(reserve.getReturnDate());
                obj.setUseDate(reserve.getUseDate());
                obj.setPayStatus(reserve.getPayStatus());
                obj.setTotalCost(reserve.getTotalCost());
                reserves.add(obj);
            }
            FleaPage<HCarReserve> fleaPage = new FleaPage<>();
            fleaPage.setCurPageData(reserves);
            fleaPage.setCurPage(paging.getCurPage());
            fleaPage.setPageSize(paging.getPageSize());
            fleaPage.setAllDataCount((int) fleaPage1.getAllDataCount());
            return ServerResponse.createBySuccess(fleaPage);
        }
        FleaPage<HCarReserve> fleaPage = new FleaPage<>();
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<FleaPage<HCarReserve>> findMyCarReserveList(FleaPage<HCarReserve> paging, HttpServletRequest request, String reserveStatus) {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        RowBounds rowBounds = new RowBounds(paging.getCurPage(), paging.getPageSize());
        List<HCarReserve> hCarReserves1 = hCarReserveMapper.selectMyCarReserveList(rowBounds, userId, reserveStatus);
        FleaPage<HCarReserve> fleaPage1 = new FleaPage<>(hCarReserves1);
        if (CollectionUtils.isNotEmpty(hCarReserves1)) {
            List<HCarReserve> reserves = Lists.newArrayList();
            for (HCarReserve reserve : hCarReserves1) {
                HCarReserve obj = new HCarReserve();
                String carReserveId = reserve.getId();
                obj.setId(carReserveId);
                ;
                obj.setUseDeptId(reserve.getUseDeptId());
//                obj.setUseDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getUseDeptId())).getDeptName());
                obj.setProvideDeptId(reserve.getProvideDeptId());
                obj.setProvideDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getProvideDeptId())).getDeptName());
                obj.setReserveStatus(reserve.getReserveStatus());
                obj.setCreateUser(reserve.getCreateUser());
                obj.setCarNumber(reserve.getCarNumber());
                obj.setCarType(reserve.getCarType());
                obj.setStartAddress(reserve.getStartAddress());
                obj.setEndAddress(reserve.getEndAddress());
                obj.setReturnDate(reserve.getReturnDate());
                obj.setUseDate(reserve.getUseDate());
                obj.setPayStatus(reserve.getPayStatus());
                obj.setTotalCost(reserve.getTotalCost());
                List<HCarReservePayinfo> payinfos = hCarReservePayinfoMapper.selectByCarReverseId(carReserveId);
                Float pays = 0.f;
                if (CollectionUtils.isNotEmpty(payinfos)) {
                    for (HCarReservePayinfo p : payinfos) {
                        pays += p.getPayMoney();
                    }
                    obj.setReturnPay(pays);
                }else {
                    obj.setReturnPay(pays);
                }
                reserves.add(obj);
            }
            FleaPage<HCarReserve> fleaPage = new FleaPage<>();
            fleaPage.setCurPageData(reserves);
            fleaPage.setCurPage(paging.getCurPage());
            fleaPage.setPageSize(paging.getPageSize());
            fleaPage.setAllDataCount((int) fleaPage1.getAllDataCount());
            return ServerResponse.createBySuccess(fleaPage);
        }
        FleaPage<HCarReserve> fleaPage = new FleaPage<>();
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<FleaPage<HCarReserve>> findCarReserveList(FleaPage<HCarReserve> paging, HttpServletRequest request) {
        OrgDept currentUserDept = FleaOrgUtils.getCurrentUserDept(request);
        if (currentUserDept == null) {
            return ServerResponse.createBySuccess();
        }
        String serviceType = currentUserDept.getServiceType();
        String deptUuid = currentUserDept.getDeptUuid();
        RowBounds rowBounds = new RowBounds(paging.getCurPage(), paging.getPageSize());
        String reserveStatus = HConstant.D_CAR_RESERVE_STATUS_YES;
        switch (serviceType) {
            //车队
            case HConstant.D_SERVICE_ORG_FLEET:
                String payStatus = HConstant.D_CAR_PAY_STATUS_YES;
                reserveStatus = HConstant.D_CAR_RESERVE_STATUS_END;
                List<HCarReserve> hCarReserves = hCarReserveMapper.selectFleetDeptUuid(rowBounds, deptUuid, reserveStatus, payStatus);
                FleaPage<HCarReserve> fleaPage5 = new FleaPage<>(hCarReserves);
                if (CollectionUtils.isNotEmpty(hCarReserves)) {
                    List<HCarReserve> reserves = Lists.newArrayList();
                    for (HCarReserve reserve : hCarReserves) {
                        HCarReserve obj = new HCarReserve();
                        obj.setId(reserve.getId());
                        ;
                        obj.setUseDeptId(reserve.getUseDeptId());
                        obj.setUseDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getUseDeptId())).getDeptName());
                        obj.setProvideDeptId(reserve.getProvideDeptId());
//                        obj.setProvideDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getProvideDeptId())).getDeptName());
                        obj.setReserveStatus(reserve.getReserveStatus());
                        obj.setCreateUser(reserve.getCreateUser());
                        obj.setCarNumber(reserve.getCarNumber());
                        obj.setCarType(reserve.getCarType());
                        obj.setStartAddress(reserve.getStartAddress());
                        obj.setEndAddress(reserve.getEndAddress());
                        obj.setReturnDate(reserve.getReturnDate());
                        obj.setUseDate(reserve.getUseDate());
                        obj.setPayStatus(reserve.getPayStatus());
                        obj.setTotalCost(reserve.getTotalCost());
                        reserves.add(obj);
                    }
                    FleaPage<HCarReserve> fleaPage = new FleaPage<>();
                    fleaPage.setCurPageData(reserves);
                    fleaPage.setCurPage(paging.getCurPage());
                    fleaPage.setPageSize(paging.getPageSize());
                    fleaPage.setAllDataCount((int) fleaPage5.getAllDataCount());
                    return ServerResponse.createBySuccess(fleaPage);
                }
                FleaPage<HCarReserve> fleaPage = new FleaPage<>(hCarReserves);
                return ServerResponse.createBySuccess(fleaPage);
            //组团社 供应商
            case HConstant.D_SERVICE_ORG_GROUP:
            case HConstant.D_SERVICE_ORG_SUPPLIER:
                String reserveStatus2 = HConstant.D_CAR_RESERVE_STATUS_END;
                List<HCarReserve> hCarReserves1 = hCarReserveMapper.selectByUseDeptUuid(rowBounds, deptUuid, reserveStatus,reserveStatus2);
                FleaPage<HCarReserve> fleaPage1 = new FleaPage<>(hCarReserves1);
                if (CollectionUtils.isNotEmpty(hCarReserves1)) {
                    List<HCarReserve> reserves = Lists.newArrayList();
                    for (HCarReserve reserve : hCarReserves1) {
                        HCarReserve obj = new HCarReserve();
                        obj.setId(reserve.getId());
                        obj.setUseDeptId(reserve.getUseDeptId());
//                obj.setUseDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getUseDeptId())).getDeptName());
                        obj.setProvideDeptId(reserve.getProvideDeptId());
                        obj.setProvideDeptName(Objects.requireNonNull(FleaOrgUtils.getOrgDeptByDeptUuid(reserve.getProvideDeptId())).getDeptName());
                        obj.setReserveStatus(reserve.getReserveStatus());
                        obj.setCreateUser(reserve.getCreateUser());
                        obj.setCarNumber(reserve.getCarNumber());
                        obj.setCarType(reserve.getCarType());
                        obj.setStartAddress(reserve.getStartAddress());
                        obj.setEndAddress(reserve.getEndAddress());
                        obj.setReturnDate(reserve.getReturnDate());
                        obj.setUseDate(reserve.getUseDate());
                        obj.setPayStatus(reserve.getPayStatus());
                        obj.setTotalCost(reserve.getTotalCost());
                        reserves.add(obj);
                    }
                    FleaPage<HCarReserve> fleaPage2 = new FleaPage<>();
                    fleaPage2.setCurPageData(reserves);
                    fleaPage2.setCurPage(paging.getCurPage());
                    fleaPage2.setPageSize(paging.getPageSize());
                    fleaPage2.setAllDataCount((int) fleaPage1.getAllDataCount());
                    return ServerResponse.createBySuccess(fleaPage2);
                }
                FleaPage<HCarReserve> fleaPage4 = new FleaPage<>(hCarReserves1);
                return ServerResponse.createBySuccess(fleaPage4);
            default:
                return ServerResponse.createBySuccess();
        }
    }

    @Override
    public ServerResponse<String> addReserveInfo(String model, HttpServletRequest request) throws ParseException {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        String currentDeptId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        HCarReserve hCarReserve = JSONObject.parseObject(model, HCarReserve.class);
        DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
//        System.out.println("开始时间"+FORMATTER.format(beginTime)+"结束时间"+FORMATTER.format(endTime));
        String begin = FORMATTER.format(hCarReserve.getUseDate());
        String end = FORMATTER.format(hCarReserve.getReturnDate());
        hCarReserve.setUseDate(FORMATTER.parse(begin));
        hCarReserve.setReturnDate(FORMATTER.parse(end));
        hCarReserve.setId(FleaStringUtils.getGenerateUUID());
        hCarReserve.setCreateUser(userId);
        //预定的部门
        hCarReserve.setUseDeptId(currentDeptId);
        //设置预定状态
        hCarReserve.setReserveStatus(HConstant.D_CAR_RESERVE_STATUS_TO_DO);
        hCarReserve.setPayStatus(HConstant.D_CAR_PAY_STATUS_NO);
        int row = hCarReserveMapper.insertSelective(hCarReserve);
        if (row == 1) {
            return ServerResponse.createBySuccessMessage("操作成功");
        }
        return ServerResponse.createByErrorMessage("操作失败");
    }
}
